<template>
  <view class="page">
    <!-- 自定义Header -->
    <CustomHeader></CustomHeader>
    
    <!-- 页头 -->
    <view class="page-header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <image
            class="back-icon"
            src="/static/icons/candidate/pre_page.png"
          ></image>
        </view>
        <text class="header-title">选择简历</text>
        <view class="header-right">
          <!-- 可以放置更多按钮，暂时留空 -->
        </view>
      </view>
    </view>

    <!-- 附件列表区域 -->
    <view class="attachment-list-container">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text class="loading-text">加载中...</text>
      </view>
      
      <view class="attachment-list" v-else>
        <view 
          class="attachment-item"
          v-for="(item, index) in attachmentList"
          :key="item.id || index"
          @click="selectAttachment(item)"
        >
          <view class="attachment-info">
            <image class="attachment-icon" :src="getAttachmentIcon(item.fileType)"></image>
            <view class="attachment-details">
              <text class="attachment-name">{{ item.name }}</text>
              <text class="attachment-size">{{ item.size }}</text>
            </view>
          </view>
          <view class="attachment-actions">
            <image class="select-arrow" src="/static/icons/right-arrow-gray.png"></image>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view v-if="attachmentList.length === 0" class="empty-state">
          <image class="empty-icon" src="/static/icons/candidate/resume_attach.png"></image>
          <text class="empty-text">暂无附件简历</text>
          <text class="empty-hint">请先上传简历附件</text>
          <view class="upload-btn" @click="goToUploadPage">
            <text class="upload-btn-text">去上传</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import CustomHeader from "@/components/CustomHeader.vue";
import { getAttachmentsApi } from "@/api/user";

// 响应式数据
const attachmentList = ref([]);
const loading = ref(false);
const sessionId = ref("");
const hrId = ref("");

// 页面加载时获取参数
onLoad((options) => {
  console.log("附件简历选择页面参数:", options);
  sessionId.value = options.sessionId || "";
  hrId.value = options.hrId || "";
  
  // 获取附件列表
  getAttachmentList();
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 获取附件列表
const getAttachmentList = async () => {
  try {
    loading.value = true;
    const response = await getAttachmentsApi();
    console.log('获取附件列表成功:', response);
    
    // 转换数据格式以适配前端显示
    attachmentList.value = response.map(item => ({
      id: item.id,
      name: item.fileName,
      size: formatFileSize(item.fileSizeMb * 1024 * 1024), // 转换MB为字节再格式化
      url: item.fileUrl,
      fileType: item.fileType,
      updateTime: item.updateTime,
      fileSizeMb: item.fileSizeMb
    }));
    
  } catch (error) {
    console.error('获取附件列表失败:', error);
    uni.showToast({
      title: "获取附件列表失败",
      icon: "none",
      duration: 2000
    });
  } finally {
    loading.value = false;
  }
};

// 选择附件
const selectAttachment = (attachment) => {
  console.log('选择附件:', attachment);
  
  uni.showModal({
    title: "确认发送",
    content: `确定要发送简历"${attachment.name}"吗？`,
    success: (res) => {
      if (res.confirm) {
        sendAttachmentResume(attachment);
      }
    }
  });
};

// 发送附件简历
const sendAttachmentResume = (attachment) => {
  console.log('发送附件简历:', attachment);
  
  // 显示发送中状态
  uni.showLoading({
    title: "发送中...",
    mask: true
  });
  
  // 获取当前用户ID
  let currentUserId = "";
  try {
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo && userInfo.id) {
      currentUserId = userInfo.id;
    } else {
      // 使用默认值用于测试
      currentUserId = "1971803632909803521";
    }
  } catch (error) {
    console.error("获取用户信息出错:", error);
    currentUserId = "1971803632909803521";
  }
  
  // 创建附件简历消息对象（按照聊天页面的消息格式）
  const attachmentMessage = {
    id: Date.now().toString(),
    sessionId: sessionId.value,
    senderId: currentUserId,
    receiveId: hrId.value,
    msgType: 17, // 简历附件消息
    content: {
      id: attachment.id,
      userId: currentUserId,
      fileName: attachment.name,
      fileSizeMb: attachment.fileSizeMb,
      fileType: attachment.fileType,
      fileUrl: attachment.url
    },
    createTime: Date.now()
  };
  
  // 模拟发送延迟
  setTimeout(() => {
    uni.hideLoading();
    
    // 发送成功提示
    uni.showToast({
      title: "简历已发送",
      icon: "success",
      duration: 1500
    });
    
    // 将消息数据存储到全局变量中
    getApp().globalData = getApp().globalData || {};
    getApp().globalData.pendingAttachmentMessage = attachmentMessage;
    
    // 返回聊天页面
    uni.navigateBack({
      success: () => {
        console.log("返回聊天页面成功，消息已存储到全局数据");
      }
    });
    
    // TODO: 实际的发送逻辑
    // 1. 调用发送消息接口
    // 2. 通过WebSocket发送给HR
    console.log("发送附件简历消息到服务器:", attachmentMessage);
    
  }, 1000);
};

// 跳转到上传页面
const goToUploadPage = () => {
  uni.navigateTo({
    url: '/pages/candidate/attachmentResume'
  });
};

// 根据文件类型获取对应的图标
const getAttachmentIcon = (fileType) => {
  const base = '/static/icons/candidate/';
  switch (fileType.toLowerCase()) {
    case 'pdf':
      return base + 'pdf.png';
    case 'doc':
      return base + 'doc.png';
    case 'docx':
      return base + 'docx.png';
    case 'png':
      return base + 'PNG.png';
    case 'jpg':
    case 'jpeg':
      return base + 'jpg.png';
    default:
      return base + 'file.png'; // 未知类型使用默认图标
  }
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};
</script>

<style lang="scss" scoped>
.page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 页头样式 */
.page-header {
  background-color: #ffffff;
  border-bottom: 1px solid #e0e0e0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.header-right {
  width: 60rpx;
}

/* 附件列表容器 */
.attachment-list-container {
  flex: 1;
  padding: 30rpx;
}

/* 加载状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 80rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.attachment-list {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

/* 附件项样式 */
.attachment-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s ease;
  border-radius: 8rpx;
  margin: 0 -16rpx;
  padding: 24rpx 16rpx;
}

.attachment-item:last-child {
  border-bottom: none;
}

.attachment-item:active {
  background-color: #f5f5f5;
}

.attachment-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.attachment-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 24rpx;
}

.attachment-details {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.attachment-name {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.attachment-size {
  font-size: 24rpx;
  color: #999;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.attachment-actions {
  display: flex;
  align-items: center;
}

.select-arrow {
  width: 24rpx;
  height: 24rpx;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  opacity: 0.3;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
  margin-bottom: 16rpx;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.empty-hint {
  font-size: 28rpx;
  color: #ccc;
  margin-bottom: 40rpx;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.upload-btn {
  background-color: #00bdb4;
  padding: 20rpx 40rpx;
  border-radius: 40rpx;
  cursor: pointer;
  transition: all 0.2s ease;
}

.upload-btn:active {
  background-color: #00a89a;
  transform: scale(0.98);
}

.upload-btn-text {
  font-size: 28rpx;
  color: #ffffff;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
</style>
